<template>
	<view class="lifecycle-page">
		<!-- 头部信息 -->
		<view class="customer-header">
			<view class="customer-info">
				<text class="name">{{ customerInfo.customerName }}</text>
				<text class="phone">{{ customerInfo.phone }}</text>
			</view>
			<view class="consultant-info">
				顾问：{{ customerInfo.consultantName }}
			</view>
		</view>

		<!-- Tab切换 -->
		<view class="tab-section">
			<view class="tab-container">
				<view 
					class="tab-item" 
					:class="{ active: currentTab === 'sale' }"
					@click="switchTab('sale')"
				>
					<text class="tab-text">售房部生命周期</text>
					<view class="tab-line" v-if="currentTab === 'sale'"></view>
				</view>
				<view 
					class="tab-item" 
					:class="{ active: currentTab === 'agent' }"
					@click="switchTab('agent')"
				>
					<text class="tab-text">报备</text>
					<view class="tab-line" v-if="currentTab === 'agent'"></view>
				</view>
			</view>
		</view>

		<!-- 筛选排序 -->
		<!-- <view class="filter-section">
			<view class="sort-options">
				<text 
					class="sort-item" 
					:class="{ active: sortType === 'time' }"
					@click="setSortType('time')"
				>
					按时间
					<text class="sort-icon" v-if="sortType === 'time'">
						{{ sortOrder === 'desc' ? '↓' : '↑' }}
					</text>
				</text>
				<text 
					class="sort-item" 
					:class="{ active: sortType === 'type' }"
					@click="setSortType('type')"
				>
					按类型
				</text>
			</view>
		</view> -->

		<!-- 时间轴列表 -->
		<view class="timeline">
			<view 
				class="timeline-item" 
				v-for="(item, index) in sortedList" 
				:key="item.eventTime"
				:class="{ important: item.isImportant }"
			>
				<!-- 时间轴节点 -->
				<view class="timeline-node">
					<view class="node-dot" :class="item.nodeDotClass"></view>
					<view class="node-line" v-if="index !== sortedList.length - 1"></view>
				</view>

				<!-- 内容卡片 -->
				<view class="content-card">
					<!-- 头部信息 -->
					<view class="card-header">
						<view class="event-type">
							<text class="type-badge" :class="item.eventTypeClass">
								{{ getEventTypeText(item.eventType) }}
							</text>
							<text class="important-tag" v-if="item.isImportant">重要</text>
							<!-- 中介信息标签 -->
							<text class="agent-tag" v-if="currentTab === 'agent' && item.agentName">
								中介：{{ item.agentName }}
							</text>
						</view>
						<view class="event-time">
							{{ formatEventTime(item.eventTime) }}
						</view>
					</view>

					<!-- 中介端特有信息 -->
					<view class="agent-info" v-if="currentTab === 'agent' && item.agentInfo">
						<view class="detail-item" v-if="item.agentInfo.shopName">
							<text class="label">中介门店：</text>
							<text class="value">{{ item.agentInfo.shopName }}</text>
						</view>
						<view class="detail-item" v-if="item.agentInfo.agentPhone">
							<text class="label">中介电话：</text>
							<text class="value">{{ item.agentInfo.agentPhone }}</text>
						</view>
						<view class="detail-item" v-if="item.agentInfo.protectionPeriod">
							<text class="label">保护期：</text>
							<text class="value" :class="item.protectionPeriodClass">
								{{ getProtectionPeriodText(item.agentInfo.protectionPeriod) }}
							</text>
						</view>
					</view>

					<view class="detail-item" v-if="item.visitType">
						<text class="label">联系方式：</text>
						<text class="value">{{ getVisitTypeText(item.visitType) }}</text>
					</view>

					<!-- 事件描述 -->
					<view class="event-description">
						{{ item.eventDescription || '暂无描述' }}
					</view>

					<!-- 附件展示 -->
					<view class="attachments" v-if="item.imageUrls && item.imageUrls.length > 0">
						<view class="attachments-title">相关图片：</view>
						<scroll-view class="images-scroll" scroll-x="true">
							<view class="images-list">
								<image 
									v-for="(img, imgIndex) in item.imageUrls" 
									:key="imgIndex"
									:src="img" 
									class="attachment-image"
									mode="aspectFill"
									@click="previewImage(item.imageUrls, imgIndex)"
								></image>
							</view>
						</scroll-view>
					</view>

					<view class="attachments" v-if="item.documentUrls && item.documentUrls.length > 0">
						<view class="attachments-title">相关文档：</view>
						<view class="documents-list">
							<view 
								v-for="(doc, docIndex) in item.documentUrls" 
								:key="docIndex"
								class="document-item"
								@click="previewDocument(doc)"
							>
								<text class="document-icon">📄</text>
								<text class="document-name">{{ getFileName(doc) }}</text>
							</view>
						</view>
					</view>

					<!-- 操作人信息 -->
					<view class="operator-info">
						<text class="operator">操作人：{{ item.operatorName }}</text>
					</view>
				</view>
			</view>
		</view>

		<!-- 空状态 -->
		<view class="empty-state" v-if="sortedList.length === 0">
			<text class="empty-icon" v-if="currentTab === 'sale'">📊</text>
			<text class="empty-icon" v-if="currentTab === 'agent'">🏠</text>
			<text class="empty-text">{{ getEmptyText() }}</text>
		</view>
	</view>
</template>

<script>
	export default {
		data() {
			return {
				currentTab: 'sale', // 'sale' 售房部, 'agent' 她报到
				saleList: [], // 售房部生命周期记录
				agentList: [], // 中介端生命周期记录
				sortType: 'time', // time, type, important
				sortOrder: 'desc', // desc, asc
				customerInfo: {
					customerName: '',
					customerPhone: '',
					consultantName: ''
				}
			}
		},
		computed: {
			// 当前显示的列表
			currentList() {
				return this.currentTab === 'sale' ? this.saleList : this.agentList;
			},
			
			// 排序后的列表
			sortedList() {
				let sorted = [...this.currentList];
				
				switch (this.sortType) {
					case 'time':
						sorted.sort((a, b) => {
							const timeA = new Date(a.eventTime).getTime();
							const timeB = new Date(b.eventTime).getTime();
							return this.sortOrder === 'desc' ? timeB - timeA : timeA - timeB;
						});
						break;
						
					case 'type':
						sorted.sort((a, b) => {
							return a.eventType - b.eventType;
						});
						break;
						
					case 'important':
						sorted.sort((a, b) => {
							if (a.isImportant && !b.isImportant) return -1;
							if (!a.isImportant && b.isImportant) return 1;
							return new Date(b.eventTime).getTime() - new Date(a.eventTime).getTime();
						});
						break;
				}
				
				sorted.map(item=>{
					item.nodeDotClass = this.getNodeDotClass(item)
					item.eventTypeClass = this.getEventTypeClass(item.eventType)
					if(item?.agentInfo?.protectionPeriod){
						item.protectionPeriodClass = this.getProtectionPeriodClass(item.agentInfo.protectionPeriod)
					}
					return item
				})
				
				return sorted;
			}
		},
		onLoad(query) {
			this.loadSaleData(query.id);
			this.customerInfo = uni.getStorageSync('hisCustomer')
		},
		methods: {
			// 切换Tab
			switchTab(tab) {
				if (this.currentTab === tab) return;
				
				this.currentTab = tab;
				
				// 如果是切换到中介端且还没有加载过数据，则加载数据
				if (tab === 'agent' && this.agentList.length === 0) {
					this.loadAgentData();
				}
			},

			// 加载售房部数据
			async loadSaleData(id) {
				try {
					const res = await this.$cloudOBjAjax('customer-lifecycle-history', 'getCustomerLifecycle', {
						customerId: id,
						getAll: true
					})
					
					this.saleList = res.list || [];
					
					// 设置客户基本信息（取第一条记录的信息）
					if (this.saleList.length > 0) {
						const firstItem = this.saleList[0];
					}
					
				} catch (error) {
					console.error('获取售房部生命周期记录失败:', error);
					uni.showToast({
						title: '加载失败',
						icon: 'none'
					});
				}
			},

			// 加载中介端数据
			async loadAgentData(id) {
				let phone = this.customerInfo.customerPhone
				if(!phone){
					return
				}
				try {
					uni.showLoading({ title: '加载中...' });
					
					// 假设接口名称为 getAgentLifecycle
					const res = await this.$cloudOBjAjax('customer-lifecycle-history', 'getAgentLifecycle', {
						phone: phone,
						eventType:[2,42],
						getAll: true
					})
					
					this.agentList = res.list || [];
					
				} catch (error) {
					console.error('获取中介端生命周期记录失败:', error);
					uni.showToast({
						title: '加载失败',
						icon: 'none'
					});
				} finally {
					uni.hideLoading();
				}
			},

			// 模拟中介端数据（开发用）

			// 设置排序类型
			setSortType(type) {
				if (this.sortType === type) {
					// 如果是时间排序，切换升降序
					if (type === 'time') {
						this.sortOrder = this.sortOrder === 'desc' ? 'asc' : 'desc';
					}
				} else {
					this.sortType = type;
					this.sortOrder = 'desc';
				}
			},

			// 获取事件类型文本
			getEventTypeText(type) {
				const typeMap = {
					1: "录入信息",
					2: "预约到访",
					3: "客户登记",
					4: "分配顾问",
					5: "接待客户",
					6: "绑定客户",
					7: "解绑",
					8: "意向金缴纳",
					9: "签订认购书",
					10: "签订购房合同",
					11: "付款",
					12: "贷款办理",
					13: "交房",
					14: "成交完成",
					15: "客户流失",
					16: "重新激活",
					17: "随访跟进",
					41:"跟进不及时",
					42:"中介置为无效",
					22:"认购"
				};
				return typeMap[type] || `未知类型(${type})`;
			},

			// 获取事件类型样式类
			getEventTypeClass(type) {
				// 按业务阶段分组设置颜色
				if ([1, 2, 3].includes(type)) {
					return 'type-info'; // 信息录入阶段 - 蓝色
				} else if ([4, 5, 6,22].includes(type)) {
					return 'type-assign'; // 分配接待阶段 - 绿色
				} else if (type === 7 || type === 41 || type === 42) {
					return 'type-unbind'; // 解绑 - 红色
				} else if ([8, 9, 10, 11].includes(type)) {
					return 'type-payment'; // 交易支付阶段 - 橙色
				} else if ([12, 13].includes(type)) {
					return 'type-process'; // 办理流程 - 紫色
				} else if (type === 14) {
					return 'type-complete'; // 完成 - 深绿色
				} else if (type === 15) {
					return 'type-lost'; // 流失 - 灰色
				} else if (type === 16) {
					return 'type-reactivate'; // 重新激活 - 青色
				} else if (type === 17) {
					return 'type-follow'; // 随访 - 浅蓝色
				} else {
					return 'type-default';
				}
			},

			// 获取节点圆点样式
			getNodeDotClass(item) {
				if (this.currentTab === 'agent') {
					return 'agent-dot';
				}
				return item.isImportant ? 'important-dot' : 'normal-dot';
			},

			// 格式化事件时间
			formatEventTime(timeStr) {
				if (!timeStr) return '';
				
				const date = new Date(timeStr);
				const now = new Date();
				const today = new Date(now.getFullYear(), now.getMonth(), now.getDate());
				const eventDate = new Date(date.getFullYear(), date.getMonth(), date.getDate());
				
				const diffTime = today - eventDate;
				const diffDays = Math.floor(diffTime / (1000 * 60 * 60 * 24));
				
				if (diffDays === 0) {
					return `今天 ${this.formatTime(date)}`;
				} else if (diffDays === 1) {
					return `昨天 ${this.formatTime(date)}`;
				} else if (diffDays < 7) {
					return `${diffDays}天前 ${this.formatTime(date)}`;
				} else {
					return `${date.getFullYear()}-${date.getMonth() + 1}-${date.getDate()} ${this.formatTime(date)}`;
				}
			},

			// 格式化时间部分
			formatTime(date) {
				const hours = date.getHours().toString().padStart(2, '0');
				const minutes = date.getMinutes().toString().padStart(2, '0');
				return `${hours}:${minutes}`;
			},

			// 获取联系方式文本
			getVisitTypeText(visitType) {
				const typeMap = {
					'visit': '到访',
					'call': '电话',
					'wechat': '微信'
				};
				return typeMap[visitType] || visitType;
			},

			// 获取保护期状态样式
			getProtectionPeriodClass(protectionPeriod) {
				if (!protectionPeriod) return '';
				return protectionPeriod.isValid ? 'protection-valid' : 'protection-invalid';
			},

			// 获取保护期文本
			getProtectionPeriodText(protectionPeriod) {
				if (!protectionPeriod || !protectionPeriod.start) return '无保护期';
				
				if (protectionPeriod.isValid) {
					return `保护期至 ${protectionPeriod.end}`;
				} else {
					return '保护期已过期';
				}
			},

			// 获取空状态文本
			getEmptyText() {
				if (this.currentTab === 'sale') {
					return '暂无售房部生命周期记录';
				} else {
					return '暂无中介端生命周期记录';
				}
			},

			// 图片预览
			previewImage(urls, current) {
				uni.previewImage({
					urls: urls,
					current: current
				});
			},

			// 文档预览
			previewDocument(url) {
				uni.showModal({
					title: '打开文档',
					content: '是否打开文档？',
					success: (res) => {
						if (res.confirm) {
							uni.downloadFile({
								url: url,
								success: (downloadRes) => {
									if (downloadRes.statusCode === 200) {
										uni.openDocument({
											filePath: downloadRes.tempFilePath,
											success: function() {
												console.log('打开文档成功');
											}
										});
									}
								}
							});
						}
					}
				});
			},

			// 获取文件名
			getFileName(url) {
				return url.split('/').pop() || '未知文件';
			}
		}
	}
</script>

<style scoped lang="scss">
	.lifecycle-page {
		min-height: 100vh;
		background: #f5f6fa;
		padding: 20rpx;
	}

	.customer-header {
		background: white;
		border-radius: 16rpx;
		padding: 30rpx;
		margin-bottom: 20rpx;
		display: flex;
		justify-content: space-between;
		align-items: center;
		box-shadow: 0 4rpx 16rpx rgba(0, 0, 0, 0.08);
		
		.customer-info {
			.name {
				font-size: 32rpx;
				font-weight: bold;
				color: #333;
				display: block;
				margin-bottom: 8rpx;
			}
			
			.phone {
				font-size: 26rpx;
				color: #666;
			}
		}
		
		.consultant-info {
			font-size: 24rpx;
			color: #999;
		}
	}

	/* Tab切换样式 */
	.tab-section {
		background: white;
		border-radius: 16rpx;
		padding: 0 30rpx;
		margin-bottom: 20rpx;
		box-shadow: 0 4rpx 16rpx rgba(0, 0, 0, 0.08);
	}

	.tab-container {
		display: flex;
		border-bottom: 1rpx solid #f0f0f0;
	}

	.tab-item {
		flex: 1;
		text-align: center;
		padding: 24rpx 0;
		position: relative;
		
		&.active .tab-text {
			color: #1890ff;
			font-weight: 600;
		}
	}

	.tab-text {
		font-size: 28rpx;
		color: #666;
		transition: color 0.3s;
	}

	.tab-line {
		position: absolute;
		bottom: 0;
		left: 50%;
		transform: translateX(-50%);
		width: 80rpx;
		height: 4rpx;
		background: #1890ff;
		border-radius: 2rpx;
	}

	.filter-section {
		background: white;
		border-radius: 16rpx;
		padding: 24rpx;
		margin-bottom: 20rpx;
		box-shadow: 0 4rpx 16rpx rgba(0, 0, 0, 0.08);
	}

	.sort-options {
		display: flex;
		gap: 30rpx;
	}

	.sort-item {
		padding: 12rpx 24rpx;
		border-radius: 20rpx;
		background: #f8f9fa;
		color: #666;
		font-size: 24rpx;
		transition: all 0.3s;
		
		&.active {
			background: #667eea;
			color: white;
		}
		
		.sort-icon {
			margin-left: 8rpx;
			font-weight: bold;
		}
	}

	.timeline {
		position: relative;
	}

	.timeline-item {
		display: flex;
		margin-bottom: 30rpx;
		position: relative;
		
		&.important {
			.content-card {
				border-left: 6rpx solid #ff4757;
			}
		}
	}

	.timeline-node {
		display: flex;
		flex-direction: column;
		align-items: center;
		width: 60rpx;
		margin-right: 20rpx;
	}

	.node-dot {
		width: 20rpx;
		height: 20rpx;
		border-radius: 50%;
		border: 4rpx solid white;
		box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.2);
		z-index: 2;
		
		&.normal-dot {
			background: #667eea;
		}
		
		&.important-dot {
			background: #ff4757;
		}
		
		&.agent-dot {
			background: #ffa502;
		}
	}

	.node-line {
		flex: 1;
		width: 2rpx;
		background: #e0e0e0;
		margin-top: 10rpx;
	}

	.content-card {
		flex: 1;
		background: white;
		border-radius: 16rpx;
		padding: 30rpx;
		box-shadow: 0 4rpx 16rpx rgba(0, 0, 0, 0.08);
	}

	.card-header {
		display: flex;
		justify-content: space-between;
		align-items: flex-start;
		margin-bottom: 20rpx;
	}

	.event-type {
		display: flex;
		align-items: center;
		gap: 12rpx;
		flex-wrap: wrap;
	}

	.type-badge {
		padding: 8rpx 16rpx;
		border-radius: 12rpx;
		font-size: 22rpx;
		color: white;
		
		/* 信息录入阶段 - 蓝色系 */
		&.type-info { background: #3498db; }
		
		/* 分配接待阶段 - 绿色系 */
		&.type-assign { background: #2ecc71; }
		
		/* 解绑 - 红色 */
		&.type-unbind { background: #e74c3c; }
		
		/* 交易支付阶段 - 橙色系 */
		&.type-payment { background: #e67e22; }
		
		/* 办理流程 - 紫色系 */
		&.type-process { background: #9b59b6; }
		
		/* 完成 - 深绿色 */
		&.type-complete { background: #27ae60; }
		
		/* 流失 - 灰色 */
		&.type-lost { background: #95a5a6; }
		
		/* 重新激活 - 青色 */
		&.type-reactivate { background: #1abc9c; }
		
		/* 随访 - 浅蓝色 */
		&.type-follow { background: #3498db; }
		
		/* 默认 */
		&.type-default { background: #7f8c8d; }
	}

	.important-tag {
		padding: 6rpx 12rpx;
		background: #ff4757;
		color: white;
		border-radius: 8rpx;
		font-size: 20rpx;
	}

	.agent-tag {
		padding: 6rpx 12rpx;
		background: #ffa502;
		color: white;
		border-radius: 8rpx;
		font-size: 20rpx;
	}

	.event-time {
		font-size: 22rpx;
		color: #999;
	}

	/* 中介信息样式 */
	.agent-info {
		background: #f8f9fa;
		border-radius: 12rpx;
		padding: 20rpx;
		margin-bottom: 20rpx;
	}

	.event-description {
		font-size: 28rpx;
		color: #333;
		line-height: 1.5;
		margin-bottom: 20rpx;
	}

	.detail-item {
		display: flex;
		align-items: center;
		margin-bottom: 12rpx;
		
		&:last-child {
			margin-bottom: 0;
		}
		
		.label {
			font-size: 24rpx;
			color: #666;
			min-width: 140rpx;
		}
		
		.value {
			font-size: 24rpx;
			color: #333;
			
			&.protection-valid {
				color: #52c41a;
			}
			
			&.protection-invalid {
				color: #ff4d4f;
			}
		}
	}

	.attachments {
		margin-bottom: 20rpx;
		
		.attachments-title {
			font-size: 24rpx;
			color: #666;
			margin-bottom: 12rpx;
		}
	}

	.images-scroll {
		white-space: nowrap;
	}

	.images-list {
		display: flex;
		gap: 16rpx;
	}

	.attachment-image {
		width: 160rpx;
		height: 160rpx;
		border-radius: 8rpx;
	}

	.documents-list {
		display: flex;
		flex-direction: column;
		gap: 12rpx;
	}

	.document-item {
		display: flex;
		align-items: center;
		padding: 16rpx;
		background: #f8f9fa;
		border-radius: 8rpx;
		
		.document-icon {
			margin-right: 12rpx;
			font-size: 28rpx;
		}
		
		.document-name {
			font-size: 24rpx;
			color: #333;
			flex: 1;
			overflow: hidden;
			text-overflow: ellipsis;
			white-space: nowrap;
		}
	}

	.operator-info {
		border-top: 1rpx solid #f0f0f0;
		padding-top: 16rpx;
		
		.operator {
			font-size: 22rpx;
			color: #999;
		}
	}

	.empty-state {
		text-align: center;
		padding: 100rpx 0;
		
		.empty-icon {
			font-size: 80rpx;
			display: block;
			margin-bottom: 20rpx;
		}
		
		.empty-text {
			font-size: 28rpx;
			color: #999;
		}
	}
</style>